package com.bymboy.emos.wx.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateRange;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.bymboy.emos.wx.controller.form.CheckinForm;
import com.bymboy.emos.wx.db.dao.*;
import com.bymboy.emos.wx.db.pojo.SystemConstants;
import com.bymboy.emos.wx.db.pojo.TbCheckin;
import com.bymboy.emos.wx.db.pojo.TbFaceModel;
import com.bymboy.emos.wx.exception.EmosException;
import com.bymboy.emos.wx.service.CheckinService;
import com.bymboy.emos.wx.task.EmailTask;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * @Package: com.bymboy.emos.wx.service.impl
 * @ClassName: CheckinServiceImpl
 * @Author: My
 * @CreateTime: 2021/9/24 9:46
 * @Description:
 */
@Service
@Scope("prototype")
@Slf4j
public class CheckinServiceImpl implements CheckinService {

    @Autowired
    private SystemConstants systemConstants;

    @Resource
    private TbHolidaysDao holidaysDao;

    @Resource
    private TbWorkdayDao workdayDao;

    @Resource
    private TbCheckinDao checkinDao;

    @Resource
    private TbFaceModelDao faceModelDao;

    @Resource
    private TbUserDao userDao;

    @Resource
    private TbCityDao cityDao;

    @Value("${emos.face.checkinUrl}")
    private String checkinUrl;

    @Value("${emos.face.createFaceModelUrl}")
    private String createFaceModelUrl;

    @Value("${emos.email.hr}")
    private String hrEmail;

    @Value("${emos.code}")
    private String code;

    @Autowired
    private EmailTask emailTask;

    @Override
    public String validCanChecking(int userId, String date) {
        boolean bool1 = holidaysDao.searchTodayIsHoliday() != null;
        boolean bool2 = workdayDao.searchTodayIsWorkday() != null;

        String type = "工作日";
        //在正常情况下今天是否是节假日
        if (DateUtil.date().isWeekend()) {
            type = "节假日";
        }
        if (bool1) {
            //今天是特殊节假日
            type = "节假日";
        } else if (bool2) {
            //今天是特殊工作日
            type = "工作日";
        }

        //根据今天节假日or工作日作出相应的业务逻辑
        if (type.equals("节假日")) {
            return "节假日不需要考勤";
        } else {
            DateTime now = DateUtil.date();
            String start = DateUtil.today() + " " + systemConstants.attendanceStartTime;
            String end = DateUtil.today() + " " + systemConstants.attendanceEndTime;
            DateTime attendanceStart = DateUtil.parse(start);
            DateTime attendanceEnd = DateUtil.parse(end);
            if (now.isBefore(attendanceStart)) {
                return "没有到上班考勤开始时间";
            } else if (now.isAfter(attendanceEnd)) {
                return "超过了上班考勤结束时间";
            } else {
                HashMap<String, Object> map = new HashMap<>(4);
                map.put("userId", userId);
                map.put("date", date);
                map.put("start", start);
                map.put("end", end);
                boolean bool = checkinDao.haveCheckin(map) != null;
                return bool ? "今日已经考勤，不用重复考勤" : "可以考勤";
            }
        }
    }

    @Override
    public void checkin(CheckinForm form, int userId, String path) {
        //判断签到
        //当前时间
        DateTime d1 = DateUtil.date();
        //上班时间
        DateTime d2 = DateUtil.parse(DateUtil.today() + " " + systemConstants.attendanceTime);
        //签到结束时间
        DateTime d3 = DateUtil.parse(DateUtil.today() + " " + systemConstants.attendanceEndTime);
        int status = 1;
        if (d1.compareTo(d2) <= 0) {
            status = 1;
        } else if (d1.compareTo(d2) > 0 && d1.compareTo(d3) < 0) {
            status = 2;
        } else {
            throw new EmosException("超出考勤时间段，无法考勤");
        }

        //查询签到人的人脸模型数据
        String faceModel = faceModelDao.searchFaceModelId(userId);
        if (faceModel == null) {
            throw new EmosException("不存在人脸模型");
        } else {
            /*HttpRequest request = HttpUtil.createPost(checkinUrl);
            request.form("photo", FileUtil.file(path), "targetModel", faceModel);
            request.form("code", "HelloWorld");
            HttpResponse response = request.execute();
            if (response.getStatus() != 200) {
                log.error("人脸识别服务异常");
                throw new EmosException("人脸识别服务异常");
            }
            String body = response.body();*/
            //测试
            String body = "True";
            if ("无法识别出人脸".equals(body) || "照片中存在多张人脸".equals(body)) {
                throw new EmosException(body);
            } else if ("False".equals(body)) {
                throw new EmosException("签到无效，非本人签到");
            } else if ("True".equals(body)) {
                //获取签到地区新冠疫情风险等级
                int risk = 1;
                String city = form.getCity();
                String district = form.getDistrict();
                String address = form.getAddress();
                String country = form.getCountry();
                String province = form.getProvince();
                //查询城市简称
                if (form.getCity() != null && form.getCity().length() > 0 && form.getDistrict() != null && form.getDistrict().length() > 0) {
                    String code = cityDao.searchCode(city);
                    //查询地区风险
                    try {
                        String url = "http://m." + code + ".bendibao.com/news/yqdengji/?qu=" + district;
                        Document document = Jsoup.connect(url).get();
                        Elements elements = document.getElementsByClass("list-content");
                        if (elements.size() > 0) {
                            Element element = elements.get(0);
                            String result = element.select("p:last-child").text();
                            //"高风险"测试
                            //result = "高风险";
                            if ("高风险".equals(result)) {
                                risk = 3;
                                //发送告警邮件
                                HashMap<String, String> map = userDao.searchNameAndDept(userId);
                                String nickname = map.get("nickname");
                                String deptName = map.get("dept_name");
                                deptName = (deptName != null ? deptName : "");
                                SimpleMailMessage message = new SimpleMailMessage();
                                message.setTo(hrEmail);
                                message.setSubject("员工" + nickname + "身处高风险疫情地区警告");
                                message.setText(deptName + "员工" + nickname + "，" + DateUtil.format(new Date(), "yyyy年MM月dd日") + "处于" + form.getAddress() + "，属于新冠疫情高风险地区，请及时与该员工联系，核实情况！");
                                emailTask.sendAsync(message);
                            } else if ("中风险".equals(result)) {
                                risk = 2;
                            }
                        }
                    } catch (IOException e) {
                        log.error("执行异常", e);
                        throw new EmosException("获取风险等级失败");
                    }
                    //保存签到记录
                    TbCheckin entity = new TbCheckin();
                    entity.setUserId(userId);
                    entity.setAddress(address);
                    entity.setCountry(country);
                    entity.setProvince(province);
                    entity.setCity(city);
                    entity.setDistrict(district);
                    entity.setStatus((byte) status);
                    entity.setRisk(risk);
                    entity.setDate(DateUtil.today());
                    entity.setCreateTime(d1);
                    checkinDao.insert(entity);
                }
            }
        }
    }

    @Override
    public void createFaceModel(int userId, String path) {
        HttpRequest request = HttpUtil.createPost(createFaceModelUrl);
        request.form("photo", FileUtil.file(path));
        //因为不知道正版的code，所以无法使用docker中的基于Python的人脸识别模块
        request.form("code", code);
        HttpResponse response = request.execute();
        String body = response.body();
        if ("无法识别出人脸".equals(body) || "照片中存在多张人脸".equals(body)) {
            throw new EmosException(body);
        } else {
            TbFaceModel faceModel = new TbFaceModel();
            faceModel.setUserId(userId);
            faceModel.setFaceModel(body);
            faceModelDao.insert(faceModel);
        }
    }

    @Override
    public HashMap searchTodayCheckin(int userId) {
        HashMap map = checkinDao.searchTodayCheckin(userId);
        return map;
    }

    @Override
    public long searchCheckinDays(int userId) {
        long days = checkinDao.searchCheckinDays(userId);
        return days;
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchWeekCheckin(HashMap param) {
        ArrayList<HashMap> checkinList = checkinDao.searchWeekCheckinDays(param);
        ArrayList<String> holidaysList = holidaysDao.searchHolidaysInRange(param);
        ArrayList<String> workdayList = workdayDao.searchWorkdayInRange(param);
        DateTime startDate = DateUtil.parseDate(param.get("startDate").toString());
        DateTime endDate = DateUtil.parseDate(param.get("endDate").toString());
        DateRange range = DateUtil.range(startDate, endDate, DateField.DAY_OF_MONTH);
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        for (DateTime one : range) {
            //查看当天是工作日还是节假日
            String date = one.toString("yyyy-MM-dd");
            String type = "工作日";
            if (one.isWeekend()) {
                type = "节假日";
            }
            if (holidaysList != null && holidaysList.contains(date)) {
                type = "节假日";
            } else if (workdayList != null && workdayList.contains(date)) {
                type = "工作日";
            }

            //如果当天是工作日，查看当天考勤情况
            String status = "";
            if (type.equals("工作日") && DateUtil.compare(one, DateUtil.date()) <= 0) {
                status = "缺勤";
                boolean flag = false;
                for (HashMap<String, String> map : checkinList) {
                    if (map.containsValue(date)) {
                        status = map.get("status");
                        flag = true;
                        break;
                    }
                }
                DateTime endTime = DateUtil.parse(DateUtil.today() + " " + systemConstants.attendanceEndTime);
                String today = DateUtil.today();
                if (date.equals(today) && DateUtil.date().isBefore(endTime) && flag == false) {
                    status = "";
                }
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("date", date);
            map.put("status", status);
            map.put("type", type);
            map.put("day", one.dayOfWeekEnum().toChinese("周"));
            list.add(map);
        }

        return list;
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchMonthCheckin(HashMap param) {
        return this.searchWeekCheckin(param);
    }
}
